<script lang="ts" setup>
import { useProvider } from '~/util/ethers_manager'
import { trackingList as defaultList } from "~/config/trackingList.json";
import { ethers } from 'ethers'
import { useFactory } from '~/util/ethers_manager';
import PopupAddPair from './PopupAddPair.vue';
import themeManager from "~/util/theme_manager";
import { PairInfo, SwapInfo } from '~/models/Tracking';
const theme = themeManager.getTheme()
const router = useRouter()
const trackingList = ref([] as SwapInfo[])

// swap choose
const swapIndex = useStorage('swapIndex', 0)
const swapCurrent = computed(() => trackingList.value[swapIndex.value])

// add pair
const showPopAddPair = ref(false)
const addingPair = ref(false)

const emit = defineEmits(["open"]);

const dockAreaStyle = computed(() => {
  return {
    background: themeManager.getTheme().getColor(1),
    "border-right": `1px solid ${themeManager.getTheme().getColor(0)}`,
  };
})

const initTrackingList = () => {
  const trackingList_str = localStorage.getItem('trackingList')
  if (!trackingList_str) {
    trackingList.value = defaultList
  }
  else {
    trackingList.value = JSON.parse(trackingList_str)
  }
}

const show = async (method: string, target: string, param?: any, param2?: any) => {
  // method: add, modify
  // target: pair, provider
  console.log(method, target);
  if (method == 'add' && target == 'provider') {
    return
  } else if (method == 'modify' && target == 'provider') {
    return
  } else if (method == 'add' && target == 'pair') {
    await addPair(param)
    return
  } else if (method == 'modify' && target == 'pair') {
    await removePair(param, param2)
    return
  }
}

const saveTrackingList = () => {
  localStorage.setItem('trackingList', JSON.stringify(trackingList.value))
}

const addPair = async (payloads: {token: string, base: string }) => {
  const {token, base} = payloads
  showPopAddPair.value = false
  addingPair.value = true
  try {
    if (!token) return
    if (!base) return
    const ethersManager = useProvider(trackingList.value[swapIndex.value].provider)
    const factoryContract = useFactory(
      trackingList.value[swapIndex.value].factory,
      ethersManager.provider
    )
    const pairAddress = await factoryContract.getPair(token, base)
    console.log(`token: ${token}`);
    console.log(`base: ${base}`);
    console.log(pairAddress);
    console.log(ethersManager.provider);
    if (!pairAddress) return
    const pairInfo = await ethersManager.getPairInfo(pairAddress)
    const name = pairInfo.token0Addr.toLowerCase() == base.toLowerCase() ? `${pairInfo.token1}-${pairInfo.token0}` : `${pairInfo.token0}-${pairInfo.token1}`
    trackingList.value[swapIndex.value].pairs.push({
      name,
      token: ethers.utils.getAddress(token),
      base: ethers.utils.getAddress(base),
      address: pairAddress
    })
    saveTrackingList()
    addingPair.value = false
  }
  catch (err) {
    addingPair.value = false
    alert('添加失败')
    console.error(err);
  }
}

const removePair = async (param: any, param2: any) => {
  if (!confirm('确定要删除币对吗?')) return
  console.log('## remove apir')
  const copy = [] as any[]
  trackingList.value[param].pairs.forEach((item: any) => copy.push(item))
  trackingList.value[param].pairs = []
  copy.forEach((item, index) => {
    if (index == param2) return
    trackingList.value[param].pairs.push(item)
  })
  saveTrackingList()
}

const open = (swap: SwapInfo, pair: PairInfo) => {
  emit('open', {
    swap,
    pair
  })
}

initTrackingList()


watch(swapIndex, () => {
  
  router.go(0)
})
</script>

<template>
  <div id="dockArea" :style="dockAreaStyle">
    <PopupAddPair :show="showPopAddPair" @close="showPopAddPair=false" @confirm="addPair" />
    <div :style="{ 'border-bottom': `1px solid ${theme.getColor(0)}` }">
      <select class="select-swap" v-model="swapIndex">
        <option v-for="(swap, i) in trackingList" :value="i">{{ swap.name }}</option>
      </select>
    </div>

    <div class="pair-list">
      <div class="btn-add" @click="showPopAddPair=true">添加币对</div>
      <div
        class="pair-item"
        v-for="(pairItem, pairIndex) in swapCurrent.pairs"
        :key="`pair-${swapIndex}-${pairIndex}`"
      >
        <span @click="open(swapCurrent, pairItem)">{{ pairItem.name }}</span>
        <div class="opration-list">
          <svg
            class="menu-icon"
            width="128"
            height="128"
            viewBox="0 0 128 128"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            @click="show('modify', 'pair', swapIndex, pairIndex)"
          >
            <rect x="21" y="59" width="85" height="10" fill="#C4C4C4" />
          </svg>
        </div>
      </div>
      <div v-if="addingPair" class="p-1">添加币对中...</div>
    </div>
  </div>
</template>

<style scoped>
#dockArea {
  height: 100vh;
  width: 240px;
  flex-shrink: 0;
  display: flex;
  flex-flow: column;
}
.dock-title {
  height: 48px;
  text-align: center;
  line-height: 48px;
  font-size: 1.25rem;
}

.btn-add {
  margin-bottom: 0.5rem;
  user-select: none;
  cursor: pointer;
  background-color: #ffffff11;
  padding: 0.25rem 0.5rem;
  border-radius: 3px;
  width: fit-content;
}

.pair-list {
  padding: 0.5rem;
  flex: 1;
}

.provider-name {
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
}
.provider-name:hover .opration-list {
  visibility: visible;
}
.pair-item {
  margin-left: 0.25rem;
  user-select: none;
  cursor: pointer;
  display: flex;
  align-items: center;
}
.pair-item:hover .opration-list {
  visibility: visible;
}

.opration-list {
  display: flex;
  align-items: center;
  margin-left: 0.25rem;
  visibility: hidden;
}
.opration-list > div:not(:first-child) {
  margin-left: 0.25rem;
}

.menu-icon {
  height: 1rem;
  width: 1rem;
}

.select-swap {
  background-color: transparent;

  border: none;
  outline: none;
  margin: 0.5rem;
  width: calc(100% - 1rem);
}

.select-swap * {
  background-color: #1e5f74;
}
</style>
